package com.timothy.android.answer;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.timothy.android.BaseProcessActivity;
import com.timothy.android.answer.Bar2DAnswerActivity.VerticalBar2DView;
import com.timothy.android.util.ValueCopyUtil;
import com.timothy.answer.ChoiceResult;
import com.timothy.chart.BaseChart;
import com.timothy.chart.CanvasSetting;
import com.timothy.chart.Bar2D;
import com.timothy.statistics.PriorityStatistics;
import com.timothy.statistics.StatisticsBuilder;

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener;
import android.view.View;
import android.view.View.OnTouchListener;

public class PriorityAnswerActivity extends BaseProcessActivity implements OnDoubleTapListener, OnGestureListener,OnTouchListener{
	private static final String LOG_TAG = "PriorityAnswerActivity";
	
	PriorityStatistics statistics = null;
	List<BaseChart> chartList = new ArrayList<BaseChart>();
	List<Bar2D> barList = new ArrayList<Bar2D>();
	String[] chartColorArr = new String[]{"#ff0000","#ff7f00","#ffff00","#56ff56","#0fff0f","#007fff","#7f00ff","#ff007f"};
	String[] shadowColorArr = new String[]{"#bf0000","#bf5f00","#bfbf00","#5fbf00","#007f7f","#003f7f","#3f007f","#7f003f"};
	String questionTextColor = "#ffffff";
	int textSize = 18;
	Integer priority = 1;
	Integer prioritySum = 0;
	String message = null;
	
	GestureDetector mGestureDetector = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Bundle bundle = this.getIntent().getExtras();
		message = bundle.getString("message");
		String priorityStr = bundle.getString("priority");
		
		if(priorityStr!=null&&priorityStr.length()>0){
			priority = Integer.valueOf(priorityStr);
		}
		
		Log.i(LOG_TAG,"priority:"+priority);
		
		if(message == null){
			return;
		}
		Log.i(LOG_TAG,message);
		
		statistics = StatisticsBuilder.parsePriorityStatistics(message);
		Map<Integer,List<ChoiceResult>> priorityMap = statistics.getPriorityMap();
		
		
		List<ChoiceResult> crList;
		if(priorityMap!=null&&priorityMap.size()>0){
			prioritySum = priorityMap.size();
			
			
			crList = priorityMap.get(priority);
			for(ChoiceResult cr:crList){
				BaseChart chart = new BaseChart();
				int index = cr.getIndex();
				Log.i(LOG_TAG,"index:"+index);
				chart.setIndex(index);
				chart.setVotes(cr.getCount());
				chart.setShare(cr.getShare());
				
//				chart.setChoiceText(String.valueOf(cr.getIndex()));
				chart.setFullColor(chartColorArr[index%8]);
				chart.setShadowColor(shadowColorArr[index%8]);
				
				chart.setChoiceText(cr.getContent());
				chart.setChoiceTextSize(textSize);
				chart.setChoiceTextColor(chartColorArr[index%8]);
				
				chart.setAnswerType(3);
				chart.setAnswerText(3);
				chart.setAnswerTextColor(chartColorArr[index%8]);
				chart.setAnswerTextSize(textSize);
				chartList.add(chart);
			}
		}
		
		//get answer data list
		for(int i=0;i<chartList.size();i++){
			BaseChart baseChart = chartList.get(i);
			Bar2D bar2D = new Bar2D();
			try {
				ValueCopyUtil.valueCopy(baseChart, bar2D);
			} catch (Exception e) {
				e.printStackTrace();
			}
			Log.i(LOG_TAG,bar2D.toString());
			barList.add(bar2D);
		}
		
		SurfaceView view = new VerticalBar2DView(this);
		
		setContentView(view);
		view.setOnTouchListener(this);
		view.setLongClickable(true);
		mGestureDetector = new GestureDetector((OnGestureListener) this); 
		
	}
	
	class VerticalBar2DView extends SurfaceView implements SurfaceHolder.Callback {
		private SurfaceHolder mHolder;
		private Canvas canvas;

		@Override
		public boolean onTouchEvent(MotionEvent event) {
			recoverBrightness();
			return super.onTouchEvent(event);
		}
		
		public VerticalBar2DView(Context context) {
			super(context);
			mHolder = getHolder();
			mHolder.addCallback(this);// 设置Surface生命周期回调
		}

		public void surfaceCreated(SurfaceHolder holder) {
			canvas = mHolder.lockCanvas();// 获得画布
			
			int canvasHeight = canvas.getHeight();
			int canvasWidth = canvas.getWidth();
			Log.i(LOG_TAG, "VerticalBar2DView:Canvas Height:"+canvasHeight);
			Log.i(LOG_TAG, "VerticalBar2DView:Canvas Width:"+canvasWidth);
			
			CanvasSetting setting = new CanvasSetting(canvasHeight,canvasWidth,Color.BLACK,1);
			
			//set canvas background color
			canvas.drawColor(setting.getBgColor());// 设置画布背景为黑色
			
			Paint mPaint = new Paint();
			
			//根据图形个数既图形间距计算出图形宽度
			int canvasNoMarginWidth = canvasWidth - setting.getLeftMargin() - setting.getRightMargin();
			double barWidthInclSpace = (canvasNoMarginWidth * 1.0)/barList.size();
			int barWidth = (int)(barWidthInclSpace*0.9);
			int spaceWidth = (int)(barWidthInclSpace*0.1);
			if(spaceWidth<1) spaceWidth = 1;
			Log.i(LOG_TAG, "VerticalBar2DView:barWidth:"+barWidth);
			Log.i(LOG_TAG, "VerticalBar2DView:spaceWidth:"+spaceWidth);
			
			setting.setSpace(spaceWidth);
			
			for(int i=0;i<barList.size();i++){
				Bar2D bar2D = barList.get(i);
				
				//根据总票数，计算出比例，再乘以画布的高度
				int votes = bar2D.getVotes();
				double votesShare = bar2D.getShare();
				Log.i(LOG_TAG, "VerticalBar2DView:votes:"+votes);
				Log.i(LOG_TAG, "VerticalBar2DView:votesShare:"+votesShare);
				
				int barHeigth = (int) (votesShare * (canvasHeight-setting.getTopMargin()-setting.getBottomMargin()));
				Log.i(LOG_TAG, "VerticalBar2DView:barHeigth:"+barHeigth);
				
				int tlX = (int) (setting.getLeftMargin()+ i * (barWidth + setting.getSpace()));
				int tlY =  canvasHeight - setting.getBottomMargin() - barHeigth;
				int brX = tlX + barWidth;
				int brY = canvasHeight - setting.getBottomMargin();
				
				//draw bar
				Log.i(LOG_TAG, "VerticalBar2DView:tlX,tlY,brX,brY="+tlX+","+tlY+","+brX+","+brY+",");
				Log.i(LOG_TAG, "VerticalBar2DView:fullColor="+bar2D.getFullColor());
				mPaint.setColor(Color.parseColor(bar2D.getFullColor()));
				canvas.drawRect(tlX,tlY,brX,brY, mPaint);
				canvas.save();
				
				//draw choice text
				Log.i(LOG_TAG, "VerticalBar2DView:ChoiceTextSize="+bar2D.getChoiceTextSize());
				Log.i(LOG_TAG, "VerticalBar2DView:ChoiceTextColor="+bar2D.getChoiceTextColor());
				mPaint.setTextSize(bar2D.getChoiceTextSize());
				mPaint.setColor(Color.parseColor(bar2D.getChoiceTextColor()));
				
				Log.i(LOG_TAG, "VerticalBar2DView:ChoiceText="+bar2D.getChoiceText());
				canvas.drawText(bar2D.getChoiceText(), tlX, canvasHeight-setting.getBottomMargin()/2, mPaint);
				canvas.save();
				
				//draw answer text
				Log.i(LOG_TAG, "VerticalBar2DView:AnswerTextSize="+bar2D.getAnswerTextSize());
				Log.i(LOG_TAG, "VerticalBar2DView:AnswerTextColor="+bar2D.getAnswerTextColor());
				mPaint.setTextSize(bar2D.getAnswerTextSize());
				mPaint.setColor(Color.parseColor(bar2D.getAnswerTextColor()));
				canvas.drawText(bar2D.getAnswerText(), tlX, tlY-20, mPaint);
				canvas.save();
				
			}

			//write question
			mPaint.setColor(Color.parseColor(questionTextColor));		
			mPaint.setTextSize(textSize);
			int queX = setting.getLeftMargin();
			int queY = setting.getTopMargin();
			Log.i(LOG_TAG, "VerticalBar2DView:queX:"+queX);
			Log.i(LOG_TAG, "VerticalBar2DView:queY:"+queY);
			canvas.drawText(statistics.getQuestion().getQuestionName(),queX,queY,mPaint); 
			canvas.save();
			
			//write priority
			canvas.drawText("(Priority:"+String.valueOf(priority)+")",queX,queY+50,mPaint); 
			canvas.save();
			
			canvas.restore();
			mHolder.unlockCanvasAndPost(canvas);// 完成绘图后解锁递交画布视图
		}
		
		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
		}
		
		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			
		}
	}

    private int verticalMinDistance = 10;
    private int minVelocity         = 0;
    
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		return mGestureDetector.onTouchEvent(event);
	}

	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// TODO Auto-generated method stub
        if (e1.getX() - e2.getX() > verticalMinDistance && Math.abs(velocityX) > minVelocity) {
        	Log.i(LOG_TAG,"Move Left");
           	if(priority<prioritySum){
        		Intent intent = new Intent();
        	    intent.setClass(this.getBaseContext(), PriorityAnswerActivity.class);
        		Bundle bundle = new Bundle();
        	    bundle.putString("message",message);
        	    bundle.putString("priority",String.valueOf(priority+1));
        	    intent.putExtras(bundle);
        	    startActivity(intent);        		
        	}
        } else if (e2.getX() - e1.getX() > verticalMinDistance && Math.abs(velocityX) > minVelocity) {
        	Log.i(LOG_TAG,"Move Right");
        	if(priority>1){
        		Intent intent = new Intent();
        	    intent.setClass(this.getBaseContext(), PriorityAnswerActivity.class);
        		Bundle bundle = new Bundle();
        	    bundle.putString("message",message);
        	    bundle.putString("priority",String.valueOf(priority-1));
        	    intent.putExtras(bundle);
        	    startActivity(intent);        		
        	}
        }
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onDoubleTap(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onDoubleTapEvent(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onSingleTapConfirmed(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}
	
	
	
}
